package com.lc.recovery.ui.activity.recoveryhome;

import android.content.Intent;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.lc.base.BaseDialog;
import com.lc.recovery.R;
import com.lc.recovery.app.AppActivity;
import com.lc.recovery.bean.AddShopBean;
import com.lc.recovery.bean.RecoveryBean;
import com.lc.recovery.http.request.OrderPriceApi;
import com.lc.recovery.http.request.Orders2Api;
import com.lc.recovery.http.request.OrdersApi;
import com.lc.recovery.http.request.OrdersMemberNameApi;
import com.lc.recovery.http.request.ShopsApi;
import com.lc.recovery.http.request.ShopsInfoApi;
import com.lc.recovery.http.response.OrdersMemberNameBean;
import com.lc.recovery.http.response.PublicMsg;
import com.lc.recovery.http.response.ShopsBean;
import com.lc.recovery.http.response.ShopsInfoBean;
import com.lc.recovery.http.response.ShopsTopBean;
import com.lc.recovery.other.IntentKey;
import com.lc.recovery.ui.dialog.MessageDialog;
import com.lc.recovery.util.BigDecimalUtils;
import com.lc.recovery.util.CourseUtils;
import com.lc.recovery.util.MyUtils;
import com.lc.recovery.util.SPUtil;
import com.lc.recovery.zxing.activity.MipcaActivityCapture;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RecoveryShopActivity extends AppActivity implements TextView.OnEditorActionListener {
    @BindView(R.id.rv_recoveryshop)
    RecyclerView rvRecoveryshop;
    @BindView(R.id.rv_recoveryrequirement)
    RecyclerView rvRecoveryrequirement;
    @BindView(R.id.et_weight)
    EditText etWeight;
    @BindView(R.id.tv_recovery_name)
    TextView tvRecoveryName;
    @BindView(R.id.tv_heji)
    TextView tvHeji;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_yaoqiu)
    TextView tvYaoqiu;


    @BindView(R.id.rl_rootView)
    RelativeLayout llRootView;
    @BindView(R.id.rv_weight)
    RecyclerView rvWeight;
    @BindView(R.id.tv_shopprice)
    TextView tvShopprice;
    @BindView(R.id.tv_totoalprice)
    TextView tvTotoalprice;
    @BindView(R.id.rv_select_weight)
    RecyclerView rvSelectWeight;
    @BindView(R.id.rl_bottom)
    RelativeLayout rlBottom;
    private BaseQuickAdapter<String, BaseViewHolder> recoveryadapter;
    private BaseQuickAdapter<AddShopBean, BaseViewHolder> addadapter;
    private String pid;
    List<ShopsTopBean.DataBean> datas;
    private BaseQuickAdapter<ShopsTopBean.DataBean, BaseViewHolder> shopstopAdapter;
    private BaseQuickAdapter<ShopsBean.DataBean, BaseViewHolder> weightdapter;
    private List<ShopsBean.DataBean> shopdata=new ArrayList<>();
    private List<String> shoptoplist = new ArrayList<>();
    private List<AddShopBean> addShopList = new ArrayList<>();
    private final int SCANNIN_GREQUEST_CODE = 107;//扫描二维码
    private String priceId;
    private String title;
    private int pos;
    List<RecoveryBean> recoveryArray=new ArrayList<>();
    private String workId;
    private String type;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_recoveryshop;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        tvPrice.setText("0.00元");
        pid = getIntent().getStringExtra("id");
        type = getIntent().getStringExtra("type");
        datas = (List<ShopsTopBean.DataBean>) getIntent().getSerializableExtra("datas");

        shops(pid);

        if (CourseUtils.isNotNullOrEmpty(SPUtil.get(getContext(),IntentKey.BUSINESSUSERID,""))){
            Log.e("TAG", "onCreate: "+SPUtil.get(this,IntentKey.BUSINESSUSERID,"") );
            workId=SPUtil.get(this,IntentKey.BUSINESSUSERID,"");
            orders_member_name(SPUtil.get(this,IntentKey.BUSINESSUSERID,""));
        }


        etWeight.setOnEditorActionListener(this);
//        分类列表
        for (int i = 0; i <datas.size() ; i++) {
            if (String.valueOf(datas.get(i).getId()).equals(pid)){
                datas.get(i).setIsgrop(true);
                pos = i;
            }else {
                datas.get(i).setIsgrop(false);
            }
        }
        shopstopAdapter = new BaseQuickAdapter<ShopsTopBean.DataBean, BaseViewHolder>
                (R.layout.item_recovery_shopnew, datas) {

            @Override
            protected void convert(BaseViewHolder baseViewHolder, ShopsTopBean.DataBean dataBean) {
                baseViewHolder.setText(R.id.tv_name, dataBean.getTitle());
                if (dataBean.isIsgrop()) {
                    baseViewHolder.setBackgroundResource(R.id.ll_bg, R.color.color01B467);

                }else {
                    baseViewHolder.setBackgroundResource(R.id.ll_bg, R.color.colorf5f5f5);
                }

            }
        };

        shopstopAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {

                for (ShopsTopBean.DataBean bean :datas){
                    bean.setIsgrop(false);
                }
                ShopsTopBean.DataBean bean = datas.get(position);
                bean.setIsgrop(!bean.isIsgrop());
                shopstopAdapter.notifyDataSetChanged();
                shops(datas.get(position).getId() + "");
                shopsInfo(datas.get(position).getId() + "");
                etWeight.setText("");
                etWeight.setHint("输入重量");

                tvTotoalprice.setText("");
                tvShopprice.setText("输入价格");
            }
        });
      rvRecoveryshop.smoothScrollToPosition(pos);
        rvRecoveryshop.setAdapter(shopstopAdapter);
       //回收要求列表
        recoveryadapter = new BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_recovery_requirement, shoptoplist) {
            @Override
            protected void convert(@NotNull BaseViewHolder baseViewHolder, String s) {
                baseViewHolder.setText(R.id.tv_name, s);
            }
        };
        rvRecoveryrequirement.setAdapter(recoveryadapter);
//        添加的商品列表
        addadapter = new BaseQuickAdapter<AddShopBean, BaseViewHolder>(R.layout.item_select_weight, addShopList) {
            @Override
            protected void convert(@NotNull BaseViewHolder baseViewHolder, AddShopBean bean) {
                baseViewHolder.setText(R.id.tv_name, bean.getTitle());
                baseViewHolder.setText(R.id.tv_weight, bean.getWeigth()+"公斤");
                baseViewHolder.setText(R.id.tv_price, bean.getPrice());
                baseViewHolder.getView(R.id.rl_close).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        // 消息对话框
                        new MessageDialog.Builder(getActivity())
                                // 标题可以不用填写
                                .setTitle("提示")
                                // 内容必须要填写
                                .setMessage("是否要删除此条数据")
                                // 确定按钮文本
                                .setConfirm(getString(R.string.common_confirm))
                                // 设置 null 表示不显示取消按钮
                                .setCancel(getString(R.string.common_cancel))
                                // 设置点击按钮后不关闭对话框
                                //.setAutoDismiss(false)
                                .setListener(new MessageDialog.OnListener() {

                                    @Override
                                    public void onConfirm(BaseDialog dialog) {

                                        addShopList.remove(baseViewHolder.getPosition());
                                        recoveryArray.remove(baseViewHolder.getPosition());
                                        addadapter.notifyDataSetChanged();
                                        ontotalPrice(addShopList);
                                    }

                                    @Override
                                    public void onCancel(BaseDialog dialog) {

                                    }
                                })
                                .show();

                    }
                });
            }
        };
        rvSelectWeight.setAdapter(addadapter);
//        二级分类
        weightdapter = new BaseQuickAdapter<ShopsBean.DataBean, BaseViewHolder>(R.layout.item_recovery_shopweight, shopdata) {
            @Override
            protected void convert(@NotNull BaseViewHolder baseViewHolder, ShopsBean.DataBean bean) {
                baseViewHolder.setText(R.id.tv_name, bean.getTitle());
                baseViewHolder.setText(R.id.tv_price, bean.getPrice());

                if (bean.isIsgrop()) {
                    baseViewHolder.setImageResource(R.id.iv_iv, R.mipmap.icon_shop_pay_select);

                }else {
                    baseViewHolder.setImageResource(R.id.iv_iv, R.mipmap.icon_shop_pay);
                }
            }
        };
        weightdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                for (ShopsBean.DataBean bean :shopdata){
                    bean.setIsgrop(false);
                }
                ShopsBean.DataBean bean = shopdata.get(position);
                bean.setIsgrop(!bean.isIsgrop());
                priceId = shopdata.get(position).getId()+"";
                title = shopdata.get(position).getTitle();
                weightdapter.notifyDataSetChanged();
                etWeight.setText("");
                etWeight.setHint("输入重量");
                tvTotoalprice.setText("");

                tvShopprice.setText(shopdata.get(position).getPrice()+"");
            }
        });
        rvWeight.setAdapter(weightdapter);
        shopsInfo(pid);
        etWeight.setMovementMethod(ScrollingMovementMethod.getInstance());
    }

    private void ontotalPrice(List<AddShopBean> list) {
        if (list.size()==0){

        }
        double price=0;
        for (int i = 0; i <list.size() ; i++) {
            price+=Double.parseDouble(list.get(i).getPrice().replace("元",""));
        }
        tvPrice.setText(price+"元");
    }

    private void order_price(String pid) {
        if (etWeight.getText().toString().isEmpty()) {
            toast("请输入入库重量");
            return;
        }
        EasyHttp.post(this)
                .api(new OrderPriceApi().setPid(pid).setUser_id(SPUtil.get(this, IntentKey.USERID, "")).setWeight(BigDecimalUtils.div(etWeight.getText().toString(), "1", 2))).request(new HttpCallback<PublicMsg>(this) {

            @Override
            public void onSucceed(PublicMsg data) {
                if (data.getCode() == 200) {
                    tvTotoalprice.setText(data.getData() + "元");
                    tvPrice.setText(data.getData() + "元");
                    if (etWeight.getText().toString().trim().isEmpty()){
                        toast("请输入回收商品重量");
                        return;
                    }
                    if (tvTotoalprice.getText().toString().trim().isEmpty()){
                        toast("请选择称重类目");
                        return;
                    }
                    if (workId==null){
                        toast("请扫码确认回收人信息");
                        return;
                    }
                    AddShopBean addShopBean=new AddShopBean();
                    addShopBean.setId(priceId);
                    addShopBean.setTitle(title);
                    addShopBean.setWeigth(etWeight.getText().toString().trim());
                    addShopBean.setPrice(tvTotoalprice.getText().toString().trim());
                    addShopList.add(addShopBean);
                    addadapter.setNewData(addShopList);
                    ontotalPrice(addShopList);
                    addadapter.notifyDataSetChanged();
                    RecoveryBean recoveryBean=new RecoveryBean();
                    recoveryBean.setShops_id(addShopBean.getId());
                    recoveryBean.setWeights(addShopBean.getWeigth());

                    recoveryArray.add(recoveryBean);

                } else {
                    toast(data.getMsg());

                }


            }


            @Override
            public void onFail(Exception e) {
//                super.onFail(e);

            }
        });
    }

    private void shops(String pid) {
        EasyHttp.post(this)
                .api(new ShopsApi().setPid(pid)).request(new HttpCallback<ShopsBean>(this) {

            @Override
            public void onSucceed(ShopsBean data) {
                if (data.getCode() == 200) {
                    shopdata.clear();
                    shopdata.addAll(data.getData());
                    weightdapter.setNewData(shopdata);
                    weightdapter.notifyDataSetChanged();

                } else {
                    toast(data.getMsg());

                }


            }


            @Override
            public void onFail(Exception e) {
//                super.onFail(e);

            }
        });
    }
    private void orders_member_name(String userid){
        EasyHttp.post(this)
                .api(new OrdersMemberNameApi().setUser_id(userid)).request(new HttpCallback<OrdersMemberNameBean>(this) {

            @Override
            public void onSucceed(OrdersMemberNameBean data) {
                if (data.getCode() == 200) {
                    tvRecoveryName.setText(data.getUser());
                }


            }


            @Override
            public void onFail(Exception e) {
//                super.onFail(e);

            }
        });
    }
    private void shopsInfo(String pid) {

        EasyHttp.post(this)
                .api(new ShopsInfoApi().setPid(pid).setUser_id(SPUtil.get(this, IntentKey.USERID, ""))).request(new HttpCallback<ShopsInfoBean>(this) {

            @Override
            public void onSucceed(ShopsInfoBean data) {
                if (data.getCode() == 200) {
                    if (data.getUser() != null) {
                        tvRecoveryName.setText(data.getUser());
                    }

                    shoptoplist.clear();
                    shoptoplist.addAll(data.getWork_require());
                    recoveryadapter.setNewData(shoptoplist);
                    recoveryadapter.notifyDataSetChanged();

                    if (data.getWork_require().size() > 0) {
                        tvYaoqiu.setVisibility(View.VISIBLE);
                    } else {
                        tvYaoqiu.setVisibility(View.GONE);
                    }
                } else {
                    toast(data.getMsg());
                }


            }


            @Override
            public void onFail(Exception e) {
//                super.onFail(e);

            }
        });
    }


    private void orders() {
        if (recoveryArray.size()==0){
            toast("请添加类目");
        }
        EasyHttp.post(this)
                .api(new OrdersApi().setUser_id(workId).setWorker_id(SPUtil.get(this,IntentKey.USERID,"")).setShops(recoveryArray)).request(new HttpCallback<PublicMsg>(this) {

            @Override
            public void onSucceed(PublicMsg data) {
                if (data.getCode() == 200) {
                    toast(data.getMsg());
                    finish();
                } else {
                    toast(data.getMsg());
                }


            }


            @Override
            public void onFail(Exception e) {
//                super.onFail(e);

            }
        });
    }

    @Override
    public boolean onEditorAction(TextView textView, int actionId, KeyEvent event) {
        if (event != null && event.getAction() != KeyEvent.ACTION_DOWN) {
            return false;
        }
        if (actionId == EditorInfo.IME_ACTION_DONE
                || event == null
                || event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
            order_priceed(priceId);
        }

        return false;

    }

    private void order_priceed(String priceId) {

        if (etWeight.getText().toString().isEmpty()) {
            toast("请输入入库重量");
            return;
        }
        EasyHttp.post(this)
                .api(new OrderPriceApi().setPid(priceId).setUser_id(SPUtil.get(this, IntentKey.USERID, "")).setWeight(BigDecimalUtils.div(etWeight.getText().toString(), "1", 2))).request(new HttpCallback<PublicMsg>(this) {

            @Override
            public void onSucceed(PublicMsg data) {
                if (data.getCode() == 200) {
                    tvTotoalprice.setText(data.getData() + "元");
                    tvPrice.setText(data.getData() + "元");

                } else {
                    toast(data.getMsg());
                }
            }
            });

        }

    @OnClick({R.id.tv_add, R.id.img_erwuma, R.id.btn_true})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_add:
                order_price(priceId);

                break;
            case R.id.img_erwuma:
                XXPermissions.with(this)
                        .permission(Permission.CAMERA)
                        .request(new OnPermissionCallback() {

                            @Override
                            public void onGranted(List<String> permissions, boolean all) {
                                if (all) {
                                    Intent intent4 = new Intent();
                                    intent4.setClass(getActivity(), MipcaActivityCapture.class);

                                    startActivityForResult(intent4, SCANNIN_GREQUEST_CODE);
                                }else {

                                }
                            }
                        });

                break;
            case R.id.btn_true:
                if (type!=null){
                    if (type.equals("1")){
                        orders();
                    }else {
                        orders2();
                    }

                }

                break;
        }
    }

    private void orders2() {
        if (recoveryArray.size()==0){
            toast("请添加类目");
        }
        EasyHttp.post(this)
                .api(new Orders2Api().setUser_id(workId).setStorage_id(SPUtil.get(this,IntentKey.USERID,"")).setShops(recoveryArray)).request(new HttpCallback<PublicMsg>(this) {

            @Override
            public void onSucceed(PublicMsg data) {
                if (data.getCode() == 200) {
                    toast(data.getMsg());
                    finish();
                } else {
                    toast(data.getMsg());
                }


            }


            @Override
            public void onFail(Exception e) {
//                super.onFail(e);

            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);  //这个super可不能落下，否则可能回调不了

        switch (SCANNIN_GREQUEST_CODE) {
            case SCANNIN_GREQUEST_CODE:
                if (resultCode == getActivity().RESULT_OK) {
                    String codeString = data.getStringExtra("result");
Log.e("TAG", "onActivityResult: "+ codeString );

                    if (codeString.contains("user_id")) {

                        workId = MyUtils.readValueFromUrlStrByParamName(codeString, "user_id");
                        SPUtil.put(this,IntentKey.BUSINESSUSERID,workId);
                        orders_member_name(MyUtils.readValueFromUrlStrByParamName(codeString, "user_id"));
//                        scene();
                    }
//
//                    startActivity(new Intent(getContext(), OrderTakeMealActivity.class).putExtra("cabinetryId",codeString));


                }
                break;
        }
    }

}
